﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
using System.Windows;
using System.IO;

namespace Acceron.University.Core.Addins
{
    public class AddinManager : DependencyObject, INotifyPropertyChanged
    {

        public event PropertyChangedEventHandler PropertyChanged;


        [ImportMany]
        public List<Core.Addins.Contracts.IModuleContract> Modules 
        { 
            get 
            {
                return (List<Core.Addins.Contracts.IModuleContract>)GetValue(ModulesProperty);
            }
            private set
            {
                SetValue(ModulesProperty, value);
                NotifyPropertyChanged("Modules");
            }
        }

        private static AddinManager singleton;


        public static readonly DependencyProperty ModulesProperty =
            DependencyProperty.Register("LastName", typeof(List<Core.Addins.Contracts.IModuleContract>), typeof(AddinManager));

        public static AddinManager Instanse
        {
            get
            {
                if (singleton == null)
                {
                    singleton = new AddinManager();
                }
                return singleton; 
            }
        }

        private AddinManager()
        { 

        }

        public void LoadModules()
        {
            Compose();
        }

        public void LoadModule(string path)
        {

        }

        private void Compose()
        {
            DirectoryInfo dinfo = new DirectoryInfo(@"AddIns");
            var directories = dinfo.GetDirectories();

            var catalog = new AggregateCatalog();

            foreach (var dir in directories)
            {
                catalog.Catalogs.Add(new DirectoryCatalog(@"AddIns\" + dir.Name));
            }
            catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));

            var container = new CompositionContainer(catalog);
            container.ComposeParts(this);
        }


        protected void NotifyPropertyChanged(string sProp)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(sProp));
            }
        }
    }
}
